<template>
    <div>
        <el-dialog :close-on-click-modal="false" :show-close="false" :align-center="true" :model-value="dialogVisible"
            height="500px" width="800px" :title="formData.id ? '编辑题目 ' : '添加题目'">
            <el-form ref="form" label-width="100px" :rules="rules">
                <el-form-item label="题目类型" prop="type">
                    <el-select v-model="formData.type" placeholder="请选择题目类型" @change="handleQuestionTypeChange"
                        :disabled="formData.id ? true : false">
                        <el-option label="单项选择题" value="单项选择题" />
                        <el-option label="多项选择题" value="多项选择题" />
                        <el-option label="填空题" value="填空题" />
                        <el-option label="判断题" value="判断题" />
                        <el-option label="组合题" value="组合题" />
                    </el-select>
                </el-form-item>
                <el-form-item label="题干" prop="questionContent">
                    <div>
                        <quill-editor ref="questionEditor" contentType="html"
                            v-model:content="formData.questionContent" />
                    </div>
                </el-form-item>
                <!-- <template v-if="formData.type === '单项选择题'">
                    <el-form-item label="选项内容" prop="chioce">
                        <div class="options-container">
                            <div v-for="(ABCD, index) in chioce.ABCD" :key="index" class="option-item">
                                {{ ABCD.label }}:
                                <quill-editor contentType="text" v-model:content="ABCD.content" />
                            </div>
                        </div>
                    </el-form-item>
                     v-model="formData.answer"
                    <el-form-item label="答案" prop="answer">
                        <el-radio-group v-model="formData.answer">
                            <el-radio v-for="(ABCD, index) in chioce.ABCD" :key="index" :label="ABCD.label">
                                {{ ABCD.label }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </template> -->
                <template v-if="formData.type === '单项选择题'">
                    <el-form-item label="选项内容" prop="options">
                        <div class="options-container">
                            <div v-for="(option, index) in 4" :key="index" class="option-item">
                                {{ String.fromCharCode(65 + index) }}:
                                <quill-editor contentType="html" v-model:content="formData.options[index]"
                                    ref="editorsRef" />
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="答案" prop="answer">
                        <el-radio-group v-model="formData.answer">
                            <el-radio v-for="(option, index) in 4" :key="index"
                                :label="String.fromCharCode(65 + index)">
                                {{ String.fromCharCode(65 + index) }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </template>
                <template v-if="formData.type === '多项选择题'">
                    <el-form-item label="选项内容" prop="options">
                        <div class="options-container">
                            <div v-for="(option, index) in numArr" :key="index" class="option-item">
                                {{ String.fromCharCode(65 + index) }}:
                                <quill-editor contentType="html" v-model:content="formData.options[index]"
                                    ref="editorsRef" @change="handleEditorChange" />
                                <el-button v-if="index > 3" type="danger" @click="deleteOption(index)">删除选项</el-button>
                            </div>
                            <el-button v-if="formData.type === '多项选择题'" type="primary"
                                @click="addOption">添加选项</el-button>
                        </div>
                    </el-form-item>
                    <el-form-item label="答案" prop="answer">
                        <el-checkbox-group v-model="formData.multipleAnswer">
                            <el-checkbox v-for="(option, index) in numArr" :key="index"
                                :label="String.fromCharCode(65 + index)">
                                {{ String.fromCharCode(65 + index) }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </template>
                <template v-if="formData.type === '判断题'">
                    <el-form-item label="答案" prop="answer">
                        <el-radio-group v-model="formData.answer">
                            <!-- <el-radio label="A">正确</el-radio>
                            <el-radio label="B">错误</el-radio> -->
                            <el-radio label="正确">正确</el-radio>
                            <el-radio label="错误">错误</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </template>
                <template v-if="formData.type === '填空题'">
                    <el-form-item label="答案" prop="answer">
                        <div class="quill-container">
                            <quill-editor ref="gapFillingEditor" contentType="html" v-model:content="formData.answer"
                                :height="200" />
                        </div>
                    </el-form-item>
                </template>
                <template v-if="formData.type === '组合题'">
                    <el-form-item label="答案" prop="answer">
                        <div class="quill-container">
                            <quill-editor ref="groupEditor" contentType="html" v-model:content="formData.answer"
                                :height="200" />
                        </div>
                    </el-form-item>
                    <!-- <el-form-item label="子试题" prop="subQuestions">
                        <div v-for="(subQuestion, index) in formData.subQuestions" :key="index">
                            <div class="sub-question-item">
                                <div class="sub-question-label">子试题 {{ index + 1 }}:</div>
                                <div class="sub-question-content">
                                    <quill-editor contentType="text" v-model:content="subQuestion.questionContent" />
                                </div>
                                <div class="sub-question-answer">
                                    答案: <quill-editor contentType="text" v-model:content="subQuestion.answer" />
                                </div>
                                <div class="delete-sub-question-btn">
                                    <el-button type="danger" @click="deleteSubQuestion(index)">删除子试题</el-button>
                                </div>
                            </div>
                        </div>
                        <div class="add-sub-question-btn">
                            <el-button type="primary" @click="addSubQuestion">添加子试题</el-button>
                        </div>
                    </el-form-item> -->
                </template>

                <el-form-item label="考核内容" prop="label">
                    <el-select multiple collapse-tags collapse-tags-tooltip v-model="formData.label"
                        placeholder="请输入试题标签">
                        <!-- <el-option label="基础算法" value="基础算法" />
                        <el-option label="桟与队列" value="桟与队列" />
                        <el-option label="二叉树" value="二叉树" />
                        <el-option label="排序算法" value="排序算法" /> -->
                        <el-option v-for="(label, index) in labelArr" :key="index" :label="labelArr[index].label"
                            :value="labelArr[index].label"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="分值" prop="score">
                    <el-input style="width: 400px" v-model="formData.score" placeholder="请输入分值" />
                </el-form-item> -->
                <el-form-item label="难度" prop="difficulty">
                    <el-select v-model="formData.difficulty" placeholder="请选择这道题的难度">
                        <el-option label="困难" value="困难" />
                        <!-- <el-option label="中等偏上" value="中等偏上" /> -->
                        <el-option label="中等" value="中等" />
                        <!-- <el-option label="中等偏下" value="中等偏下" /> -->
                        <el-option label="简单" value="简单" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm">提交</el-button>
                    <el-button type="danger" @click="cancelAddOrEdit">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
import { reactive, ref, defineEmits, defineExpose, onMounted, getCurrentInstance } from 'vue';
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import { getIDTitle, insertNewTitle, updataTitleContent } from '@/api/questionBank';
import { getAllExamineContent } from '@/api/tag'
import { useRoute } from 'vue-router';
import { getIdSubject } from '@/api/subject';
import { ElMessage } from 'element-plus';

const dialogVisible = ref(false);

const formData = reactive({
    id: 0,
    type: '单项选择题',
    questionContent: '',
    options: [],
    label: [],
    score: '',
    // subQuestions: [],//装组合题的小题和答案
    answer: '',
    multipleAnswer: [],//多选题答案
    difficulty: '',
    subject: ''
});

const labelArr = ref([])
const numArr = ref(4)
const form = ref();
const questionEditor = ref();//用于题目编辑框清除
// const gapFillingEditor = ref()//用于填空题答案编辑框清除
// const groupEditor = ref()//用于组合题答案编辑清除

const handleQuestionTypeChange = () => {
    formData.answer = '';
    formData.subQuestions = [];
    formData.answer = '';
    questionEditor.value.setHTML('');
    // gapFillingEditor.value.setHTML('')
    // groupEditor.value.setHTML('')
    formData.label = [];
    formData.score = '';
    formData.difficulty = '';
    formData.multipleAnswer = []
    clearEditors()
    numArr.value = 4,
        formData.options = []
    form.value.resetFields();
};

const handleEditorChange = (content, editor) => {
    console.log(content, 'content');
    console.log(editor.getContents(), '445646');
};

// 添加选项
const addOption = () => {
    numArr.value++
    //   formData.options.push({ label: String.fromCharCode(65 + formData.options.length), content: '' });
};

// 删除选项
const deleteOption = (index) => {
    console.log(formData.multipleAnswer, 'formData.multipleAnswer1');

    //     formData.options.length = numArr.value
    //     console.log(formData.options.length,'formData.options.length');
    console.log(index, 'index');
    //   console.log(formData.options.splice(index, 1),'formData.options.splice(index, 1);');
    //   console.log(formData.options.length,'formData.options.length');
    // let j = 1
    // let maxChar = ''
    for (let i = 0; i < formData.multipleAnswer.length; i++) {


        // // while(j > 0){
        // // 将字符转换为数字值
        // const numberArray = formData.multipleAnswer.map(item => item.charCodeAt(0) - 65); // 'A'的ASCII码是65，'B'是66，依此类推
        // // 找到数字数组中的最大值
        // const maxNumber = Math.max(...numberArray);
        // // 将最大值转换回字符形式
        // const maxChar = String.fromCharCode(maxNumber + 65); // 将数字值转换为对应的字符
        // console.log(maxChar,'maxchar');
        // // j--
        // // }
        // // console.log('q');
        // if(formData.multipleAnswer[i] < maxChar){
        //         formData.multipleAnswer = formData.multipleAnswer.filter(item => item !== maxChar);
        //         console.log('555');
        //     console.log(maxChar,'88',formData.multipleAnswer);

        //     }
        //删除答案选项
        if (formData.multipleAnswer[i] === String.fromCharCode(65 + index)) {

            formData.multipleAnswer.splice(i, 1);
            i--; // 删除元素后需要将索引减一，以便继续遍历数组

        }

        if (String.fromCharCode(65 + index) < formData.multipleAnswer[i]) {
            let charCode = formData.multipleAnswer[i].charCodeAt(0); // 获取字符的ASCII码
            let newChar = String.fromCharCode(charCode - 1); // 将ASCII码减一，并转换为字符
            formData.multipleAnswer[i] = newChar
        }
        // console.log(formData.multipleAnswer[i]);
        // console.log(formData.multipleAnswer,'formData.multipleAnswer22');
    }
    // formData.multipleAnswer.forEach((subtraction) => {
    //     // 访问每个元素
    //     if( String.fromCharCode(65 + index) < subtraction){
    //         let charCode = subtraction.charCodeAt(0); // 获取字符的ASCII码
    //         let newChar = String.fromCharCode(charCode - 1); // 将ASCII码减一，并转换为字符
    //         subtraction = newChar
    //     }
    // formData.multipleAnswer.push(subtraction)
    //     console.log(subtraction);
    // });
    // console.log(formData.multipleAnswer, 'formData.multipleAnswer');
    // console.log(formData.multipleAnswer,'formData.multipleAnswer');
    // console.log(formData.options,formData.multipleAnswer,'formData.options222');
    numArr.value--
    formData.options.splice(index, 1);

    // console.log(formData.options,formData.multipleAnswer,'formData.options1111');
};

const editorsRef = ref('');
// const instance = getCurrentInstance();

onMounted(() => {
    //   editorsRef.value = $refs.editorsRef;
    // editorsRef.value = editorsRef.value.$refs.editorsRef;
    // console.log(instance.refs.editorsRef,'ins');
    // editorsRef.value = instance.refs.editorsRef;
    // console.log(editorsRef.value,'editorsRef.value');

});

const clearEditors = () => {
    editorsRef.value.forEach((editor, index) => {
        // formData.options[index] = '';
        // console.log(editor, 'editor');
        editor.setHTML('');
    });
};

// const addSubQuestion = () => {
//     formData.subQuestions.push({
//         questionContent: '',
//         answer: ''
//     });
// };

// const deleteSubQuestion = (index) => {
//     formData.subQuestions.splice(index, 1);
// };

const cancelAddOrEdit = () => {
    handleQuestionTypeChange();
    dialogVisible.value = false;
};

const route = useRoute();

const emit = defineEmits(['success','refreshAfterEdit']);

const submitForm = async () => {
    const res1 = await getIdSubject(route.params.subId);
    const res1Data = res1.data.data;
    const str = formData.multipleAnswer.join(","); // 使用逗号作为分隔符
    console.log(formData, 'formData.options');
    const formDataToSubmit = {
        id: formData.id,
        type: formData.type,
        questionContent: formData.questionContent,
        label: formData.label,
        // score: formData.score,11
        difficulty: formData.difficulty,
        multipleAnswer: str,
        answer: formData.answer,
        options: formData.options,
        subject: res1Data.subject
    };
    if (formData.type === '多项选择题') {
        formDataToSubmit.answer = formData.multipleAnswer.join(',');
    }
    console.log(formDataToSubmit.answer, 'formDataToSubmit.answer');
    console.log(str, formData.answer, 'steeee');
    // console.log(test,'test');
    console.log(formData.options, 'options');
    console.log(formData, 'formData');
    console.log(formDataToSubmit, 'formDataToSubmit');
    if (formData.id) {
        //更新题目信息
        await updataTitleContent(formDataToSubmit);
        emit('dataEdit', formDataToSubmit);
        ElMessage.success('编辑成功')
        emit('refreshAfterEdit', "kzy")
    } else {
        //把要添加的数据发送给数据库
        const res = await insertNewTitle(formDataToSubmit);
        //获取返回的题id和题的事件
        formDataToSubmit.id = res.data.data.id;
        formDataToSubmit.createdAt = res.data.data.createdAt;
        //把数据发送给listManagement组件渲染页面
        emit('success', formDataToSubmit);
        ElMessage.success('添加成功')
    }

    handleQuestionTypeChange();
    formData.type = '单项选择题'
    dialogVisible.value = false;
};

const open = async (obj) => {
    dialogVisible.value = true;
    if (obj.id) {
        // debugger
        //获取全部标签
        // const res2 = await getAllExamineContent(1)
        //获取全部考核内容显示，用来显示到页面添加或编辑的考核内容上
        // const res2 = await getAllExamineContent(route.params.subId)
        // const res1 = res2.data.data
        // labelArr.value = res1
        getAllTag()

        const res = await getIDTitle(obj.id);
        console.log(res, 'res');

        const responseData = res.data.data;
        formData.id = responseData.id;
        formData.type = responseData.type;
        formData.questionContent = responseData.questionContent;
        formData.answer = responseData.answer;
        // formData.label = responseData.T_exam_label.label;
        formData.label = responseData.label;
        // formData.score = responseData.score;11
        formData.difficulty = responseData.difficulty;

        // responseData.options.forEach((option, index) => {
        //   formData.options[index].content = option.content;
        // });
        if (formData.type === '多项选择题') {
            // for(let i = 'A'; i <= max(formData.answer);i++)
            // formData.multipleAnswer = formData.answer.split(',')     最初版
            formData.multipleAnswer = formData.answer.split('')
            // formData.answer = []
            //可以拿到26个字符，有字符的为该字符，没字符的话为空字符串
            // formData.multipleAnswer = Array.from({length: 26}, (_, i) => formData.answer.includes(String.fromCharCode(65 + i)) ? String.fromCharCode(65 + i) : ' ');
            // console.log(Math.max(...formData.answer.split('').map(char => char.charCodeAt(0))),'Math.max(...string.');


            // if (Math.max(...formData.answer.split('').map(char => char.charCodeAt(0))) - 64 > 4)
            // {

            //     numArr.value = Math.max(...formData.answer.split('').map(char => char.charCodeAt(0))) - 64
            //     console.log('numArr',numArr.value);
            // }
            // else numArr.value = 4
            formData.multipleAnswer = formData.multipleAnswer.filter(function (item) {
                return item !== ','
            })
            numArr.value = responseData.options.length
            // console.log('numArr',numArr.value);
            // console.log(numArr.value,'numArr.value');
            // for(let i = 0 ;i < formData.multipleAnswer.length;i++){
            //     if(formData.multipleAnswer[i] - 'A' === i){

            //     }
            // }

        }
        formData.options = responseData.options
        
        // console.log(formData, 'fadsfadsf');
        // console.log(formData,'55gadg');
    } else {
        // 添加
        getAllTag()
    }
};

//获取全部考核内容显示，用来显示到页面添加或编辑的考核内容上
const getAllTag = async () => {
    // const res = await getAllExamineContent(1)
    const res = await getAllExamineContent(route.params.subId)
    // console.log('112');
    // console.log(res,'resonMounted');
    // console.log(formData,'aaa');
    const res1 = res.data.data
    // console.log(res1);
    labelArr.value = res1
    // console.log(labelArr,'formData.label');
}

// onMounted(() =>{
//     getTag()
// })

defineExpose({
    open
});
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
    max-height: calc(100vh - 300px);
    overflow: auto;
}

.options-container {
    display: flex;
    flex-direction: column;

    .option-item {
        margin-bottom: 10px;
    }
}

.quill-container {
    /* height: 200px; */
    overflow: auto;
}

.sub-question-item {
    margin-bottom: 20px;

    .sub-question-label {
        font-weight: bold;
    }

    .sub-question-content {
        margin-top: 5px;
        margin-bottom: 10px;
    }

    .sub-question-answer {
        margin-top: 5px;
    }

    .delete-sub-question-btn {
        margin-top: 10px;
    }
}

.add-sub-question-btn {
    margin-left: 10px;
}
</style>
